
const fs = require('fs');
const { dialog } = require('electron');

//将文件读取为数据流
function readFileAsStream(filePath) {
    const stream = fs.createReadStream(filePath);

    stream.on('end', function () {
        console.log('End of file');
    });

    stream.on('error', function (err) {
        console.log(`Error: ${err}`);
    });
}

//将文件读取为数组
function readFile(filePath, isSync) {
    if (isSync) {
        fs.readFileSync(filePath, (err, data) => {
            if (err) {
                console.error(err);
                return null;
            } else {
                console.log(data);
                return data;
            }
        });
    }
    fs.readFile(filePath, (err, data) => {
        if (err) {
            console.error(err);
            return null;
        } else {
            console.log(data);
            return data;
        }
    });
}

//打开文件选择器
function openFileSelector(mainWindow) {
    dialog.showOpenDialog(mainWindow, {
        properties: ['openFile', 'multiSelections'],
        filters: [
            { name: 'Docx', extensions: ['docx', 'doc'] },
            { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
            { name: 'All Files', extensions: ['*'] }
        ]
    }).then((result) => {
        if (result.canceled) {
            console.log('No file selected');
        } else {
            return result.filePaths;
        }
    }).catch((err) => {
        console.log(err);
    });
    return null;
}

//打开同步文件选择器
function openFileSelectorSync(mainWindow) {
    return dialog.showOpenDialogSync(mainWindow, {
        title: '请选择线路文档',
        properties: ['openFile', 'multiSelections'],
        filters: [
            { name: 'Docx', extensions: ['docx', 'doc'] },
            { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
            { name: 'All Files', extensions: ['*'] }
        ]
    })
}

//确保文件路径存在
function ensureDirExists(dirPath, recursive) {
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: recursive });
    }
    return fs.existsSync(dirPath);
}


module.exports = {
    readFileAsStream,
    readFile,
    openFileSelector,
    openFileSelectorSync,
    ensureDirExists,
} 